<?php
namespace Admin\Controller;

/**
* 权限控制类
*/
class AuthController extends CommonController{

    //处理mini_auth_group表
    public function index(){
        $this->display();
    }

    //列表接口
    public function getdata(){
        $p = I('p') ? I('p') : 1;
        $row = I('row') ? I('row') : 10;
        
        $m = M('AuthGroup');
        $map = array();
        $data['data'] = $m->where($map)->page($p,$row)->select();

        $data['page']['total'] = $m->where($map)->count();
		$data['page']['cur'] = $p;
		$data['page']['row'] = $row;

        _apiReturn(1,'success',$data);
    }

    //编辑
    public function edit(){
        if($_GET['id']){
            $this->info = M('AuthGroup')->find($_GET['id']);
        }
        $this->display();
    }

    //编辑提交
    public function edit_post(){
        if(IS_POST){
            $m = M('AuthGroup');
            $saveTmp = $m->create($_POST);
            if($saveTmp['id']){
                if($m->save($saveTmp)){
                    _apiReturn(1,'success');
                }else{
                    _apiReturn(0,'error');
                }
            }else{
                if($m->add($saveTmp)){
                    _apiReturn(1,'success');
                }else{
                    _apiReturn(0,'error');
                }
            }
        }
    }

    //删除
    public function del(){
        $this->_del(M('AuthGroup'),I('ids'));
    }

    public function rule(){
        $this->display();
    }

    public function rule_edit(){

        $tree = new \Think\Tree();
        
        $m = M('AuthRule');

        if($_GET['group_id']){
            $info['group'] = $_GET['group_id'];
        }

        $parentid = $_GET['parentid'] ? $_GET['parentid'] : 0;
        
        
        if($parentid){
            $parent = $m->find($parentid);
            $info['group'] = $parent['group'];            
        }

        if($_GET['id']){
            $info = $m->find($_GET['id']);
            $parentid = $info['parentid'];
        }

        $map['group'] = $info['group'];
        $data = $m->where($map)->order('listorder asc')->select();
        foreach ($data as $r) {
            $r['selected'] = $r['id'] == $parentid ? 'selected' : '';
            $array[] = $r;
        }
        $str = "<option value='\$id' \$selected>\$spacer \$title</option>";
        $tree->init($array);
        $select_categorys = $tree->get_tree(0, $str);
        $this->assign("select_categorys", $select_categorys);
        
        $this->info = $info;

        $this->display();
    }

    public function rule_edit_post(){
        if(IS_POST){
            $_POST['update_time'] = Date('Y-m-d H:i:s');

            $m = M('AuthRule');
            $saveTmp = $m->create($_POST);

            if($saveTmp['id']){
                if($m->save($saveTmp)){
                    F('Rule/group_'.$_POST['group'],NULL);                    
                    _apiReturn(1,'success');
                }else{
                    _apiReturn(0,'error');
                }
            }else{
                if($m->add($saveTmp)){
                    F('Rule/group_'.$_POST['group'],NULL);                    
                    _apiReturn(1,'success');
                }else{
                    _apiReturn(0,'error');
                }
            }
        }
    }

    //删除权限
    public function del_rule(){
    	if(I('group')){
    		F('Rule/group_'.I('group'),NULL); 
    	}
    	 
        $this->_del(M('AuthRule'),I('ids'));
    }


    /**
    * @desc 根据分类ID，获取分类数据,接口
    */
    public function getdata_rule_tree(){
        // F('Cats/group_'.$_REQUEST['group_id'],NULL);
         _apiReturn(1,L('success'),AuthController::getdata_rule($_REQUEST['group_id']));
     }
 
     /**
     * 非接口
     */
     public function getdata_rule($groupid){
         $treedata = F('Rule/group_'.$groupid);
         if(!$treedata){
             $treedata = AuthController::_update_cache_tree($groupid);
         }
         return $treedata;
     }
 
     /**
      * 固化app分类树存储
      * @param unknown $appid
      * @param unknown $groupid
      */
     public function _update_cache_tree($groupid){
         $tree = new \Think\Tree();
         
         $map['group'] = $groupid;
         $m = M('AuthRule');
         $data = $m->where($map)->order('listorder asc')->select();
         $tree->init($data);
         $treedata = $tree->get_tree_array(0, $str);
         $result = AuthController::_get_node_tpl($treedata,"");
 
         F('Rule/group_'.$groupid,$result);
         return $result;
     }

     /**
	 * 配合ajax_nodes
	 * @param unknown $datas
	 * @param unknown $result
	 * @return string
	 */
	public function _get_node_tpl($datas,$result){
		$results = array();
		foreach ($datas as $data){
			$res= array(
					'id' => $data['id'],
					'parentid' => $data['parentid'],
					'name' => $data['title'],
                    'key' => $data['name'],
					'spread' => true
			);
			$results[] = $res;
			if($data['child']){
				$results[count($results)-1]['children'] = $this->_get_node_tpl($data['child'], $result);
			}
		}
		return $results;
    }
    
    public function admin_auth(){
        if($_GET['id']){
            $this->info = M('AuthGroup')->find($_GET['id']);
            $this->rules = explode(',',$this->info['rules']);
        }else{
            $this->error("无法访问");
        }
        $this->display();
    }

    public function admin_auth_post(){
        if(IS_POST){
        	
            $saveTmp = array(
                'id' => $_POST['id'],
                'rules' => implode(',',$_POST['rules'])
            );
			
            M('AuthGroup')->save($saveTmp);
            	_apiReturn(1,'success');
            
            
        }
    }
    

    public function show_rule($rule,$level,$usrules){
    	if($usrules){
    		$rulearr = explode(',',$usrules);
			if(in_array($rule['id'],$rulearr)){
				$yjccheck = "checked";
			}
    	}
        $result = '<li class="rule-level-'.$level.'"><input type="checkbox" name="rules[]" lay-filter="rule" value="'.$rule['id'].'" title="'.$rule['name'].'"  lay-skin="primary" '.$yjccheck.'>';
        if($rule['children']){
            $result .= '<ul class="ul-level-'.($level+1).'">';
            for($i = 0 ; $i < count($rule['children']);$i++){
                $result .= \Admin\Controller\AuthController::show_rule($rule['children'][$i],$level+1);
            }
            $result .= '</ul>';
        }
        $result .= '</li>';
        return $result;
    }
}